<script setup>
import { onMounted, ref } from 'vue'
import {
  deleteTestRequestApi,
  myTodoApi,
  updateStatusByIdApi
} from '@/api/testRequest.js'
import { getProjectListApi } from '@/api/project.js'
import { ElMessage } from 'element-plus'
import { getUsersByRoleIdApi } from '@/api/sysUser.js'
import { formatDate } from '@/utils/dateUtils.js'

//基础数据构
const defaultForm = {
  projectId: '',
  projectName: '',
  versionNumber: '',
  requestName: '',
  plannedTestTime: '',
  actualTestTime: null,
  smokeTestPlanUrl: '',
  description: '',
  status: 1,
  testFailedNumber: 0,
  isPostpone: false,
  postponeTime: '',
  createdBy: 0,
  developers: [],
  testers: [],
  id: '',
  createTime: '',
  updateTime: ''
}

// 定义 testRequest 为响应式对象
const testRequest = ref({ ...defaultForm })

// 定义保留字段
const fieldsToKeep = ['projectId', 'projectName', 'versionNumber']

// 定义重置函数
function resetForm() {
  const newForm = { ...defaultForm }

  Object.keys(newForm).forEach((key) => {
    if (!fieldsToKeep.includes(key)) {
      testRequest.value[key] = newForm[key]
      console.log('key ==' + key + '  value' + testRequest.value[key])
    }
  })
}
const defaultFormDto = {
  requestId: 0,
  status: 0
}

const testRequestDto = ref(defaultFormDto)

// 列表
const list = ref([])
//分页
const total = ref(0)
const pageParams = ref({
  page: 1,
  limit: 10
})
const queryDto = ref({
  projectId: '',
  versionNumber: ''
})

// 查询列表接口
const fetchData = async () => {
  const response = await myTodoApi(
    pageParams.value.page,
    pageParams.value.limit,
    queryDto.value
  )
  total.value = response.data.total
  list.value = response.data.records
}
onMounted(() => {
  //刷新项目列表
  fetchProjectOptions()
  fetchData()
  // fetchVersionForProjectOptions()
})

//项目列表
const projectOptions = ref([])
//拿到项目列表
const fetchProjectOptions = async () => {
  const response = await getProjectListApi(1, 1000, null)
  projectOptions.value = response.data.records
}

// 定义所属开发人员和测试人员
const allDevUserList = ref([])
const allQaUserList = ref([])
const devUserList = ref([])
const qaUserList = ref([])

const getUserListByRole = async () => {
  const response = await getUsersByRoleIdApi('DEV')
  allDevUserList.value = response.data

  const { data } = await getUsersByRoleIdApi('QA')
  allQaUserList.value = data
}

/**
 * 编辑
 */

const editShow = (row) => {
  testRequest.value = { ...row }
  getUserListByRole()
  console.log('devusers ===' + testRequest.value.developers)
  devUserList.value = testRequest.value.developers
  qaUserList.value = testRequest.value.testers
}

/*
删除
 */
const deleteTestRequest = async (row) => {
  await deleteTestRequestApi(row.id)
  ElMessage.success('删除成功')
  fetchData()
}

const getStatusText = (status) => {
  const statusMap = {
    1: '待提测',
    2: '已提测',
    3: '提测未通过',
    4: '提测通过'
  }
  return statusMap[status] || '未知状态' // 返回未知状态以防止不在枚举范围内的值
}

//触发提测操作
const submitTest = async (row) => {
  // 提测通过操作逻辑
  testRequestDto.value.requestId = row.id
  testRequestDto.value.status = 2
  await updateStatusByIdApi(testRequestDto.value)
  testRequestDto.value = { ...defaultFormDto }
  fetchData()
  ElMessage.success('提测成功，待测试人员进行冒烟验收')
  console.log('提测成功', row)
}
const approveTest = async (row) => {
  // 提测通过操作逻辑
  testRequestDto.value.requestId = row.id
  testRequestDto.value.status = 4
  await updateStatusByIdApi(testRequestDto.value)
  testRequestDto.value = { ...defaultFormDto }
  fetchData()
  ElMessage.success('冒烟验收通过')
}

const rejectTest = async (row) => {
  // 提测通过操作逻辑
  testRequestDto.value.requestId = row.id
  testRequestDto.value.status = 3
  await updateStatusByIdApi(testRequestDto.value)
  testRequestDto.value = { ...defaultFormDto }
  fetchData()
  ElMessage.success('提测被驳回')
  // 提测驳回操作逻辑
  console.log('提测驳回', row)
}
// 格式化函数
const dateFormatter = (row, column, cellValue) => {
  return formatDate(cellValue)
}

//   查看详情
const dialogDetailsVisible = ref(false)

const queryTestRequestDetails = (row) => {
  testRequest.value = { ...row }
  getUserListByRole()
  devUserList.value = testRequest.value.developers
  qaUserList.value = testRequest.value.testers
  dialogDetailsVisible.value = true
}

/**
 * 关闭弹窗
 */

const stopDialog = () => {
  dialogDetailsVisible.value = false
  devUserList.value = []
  qaUserList.value = []
  resetForm()
}
</script>

<template>
  <!---数据表格-->
  <el-table :data="list" style="width: 100%">
    <el-table-column prop="projectName" label="项目名称" />
    <el-table-column prop="versionNumber" label="版本号" />
    <el-table-column prop="requestName" label="提测需求名称" />
    <el-table-column prop="smokeTestPlanUrl" label="ms冒烟测试计划地址" />

    <el-table-column
      prop="plannedTestTime"
      label="计划提测时间"
      :formatter="dateFormatter"
    />
    <el-table-column prop="actualTestTime" label="实际提测时间" />
    <el-table-column prop="isPostpone" label="是否提测延期">
      <template v-slot="scope">
        {{ scope.row.isPostpone ? '是' : '否' }}
      </template>
    </el-table-column>
    <el-table-column prop="testFailedNumber" label="提测失败次数">
    </el-table-column>
    <el-table-column prop="isPostpone" label="状态">
      <template #default="scope">
        <span>
          {{ getStatusText(scope.row.status) }}
        </span>
      </template>
    </el-table-column>
    <el-table-column label="操作" align="center" width="280" #default="scope">
      <div>
        <!-- 待提测状态 -->
        <el-button
          v-if="scope.row.status === 1"
          type="primary"
          size="small"
          @click="editShow(scope.row)"
        >
          编辑
        </el-button>
        <el-button
          v-if="scope.row.status === 1"
          type="danger"
          size="small"
          @click="deleteTestRequest(scope.row)"
        >
          删除
        </el-button>
        <el-button
          v-if="scope.row.status === 1"
          type="success"
          size="small"
          @click="submitTest(scope.row)"
        >
          提测
        </el-button>

        <!-- 已提测状态 -->
        <el-button
          v-if="scope.row.status === 2"
          type="success"
          size="small"
          @click="approveTest(scope.row)"
        >
          提测通过
        </el-button>
        <el-button
          v-if="scope.row.status === 2"
          type="danger"
          size="small"
          @click="rejectTest(scope.row)"
        >
          提测驳回
        </el-button>

        <!-- 提测未通过状态 -->
        <el-button
          v-if="scope.row.status === 3"
          type="success"
          size="small"
          @click="submitTest(scope.row)"
        >
          重新提测
        </el-button>

        <!-- 非待提测状态 -->
        <el-button
          v-if="scope.row.status !== 1"
          type="success"
          size="small"
          @click="queryTestRequestDetails(scope.row)"
        >
          详情
        </el-button>
      </div>
    </el-table-column>
  </el-table>
  <el-pagination
    :page-sizes="[10, 20, 50, 100]"
    layout="total, sizes, prev, pager, next"
    :total="total"
    v-model:current-page="pageParams.page"
    v-model:page-size="pageParams.limit"
    @size-change="fetchData"
    @current-change="fetchData"
  />

  <!--  详情弹窗-->
  <el-dialog v-model="dialogDetailsVisible" title="详情" width="40%">
    <el-form label-width="120px">
      <el-form-item label="所属项目">
        <el-input v-model="testRequest.projectName" disabled />
      </el-form-item>
      <el-form-item label="所属版本">
        <el-input v-model="testRequest.versionNumber" disabled />
      </el-form-item>
      <el-form-item label="提测需求名称">
        <el-input v-model="testRequest.requestName" disabled></el-input>
      </el-form-item>

      <el-form-item label="计划提测时间" prop="plannedTestTime">
        <el-date-picker
          v-model="testRequest.plannedTestTime"
          type="date"
          placeholder="选择日期"
          disabled
        />
      </el-form-item>
      <el-form-item label="ms冒烟测试计划">
        <el-input disabled v-model="testRequest.smokeTestPlanUrl"></el-input>
      </el-form-item>

      <el-form-item label="所属开发人员">
        <el-select
          v-model="devUserList"
          multiple
          placeholder="选择需求负责的开发人员"
          style="width: 240px"
          disabled
        >
          <el-option
            v-for="item in allDevUserList"
            :key="item.id"
            :label="item.username"
            :value="item.id"
            disabled
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属测试人员">
        <el-select
          v-model="qaUserList"
          multiple
          placeholder="选择负责需求的测试人员"
          style="width: 240px"
          disabled
        >
          <el-option
            v-for="item in allQaUserList"
            :key="item.id"
            :label="item.username"
            :value="item.id"
            disabled
          />
        </el-select>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="testRequest.description"
          type="textarea"
          :rows="4"
          placeholder="请输入描述"
          disabled
        />
      </el-form-item>
      <el-form-item class="dialog-footer">
        <el-button type="primary" @click="stopDialog">关闭</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
